<?php

/**
 * ActiveRecord class
 *
 * @author Julot
 * @since Thursday, April 12, 2012. 01:39 PM
 */
class ActiveRecord extends CActiveRecord {

	public function behaviors() {
		$behaviors = array(
			'CTimestampBehavior'=>array(
				'class'=>'zii.behaviors.CTimestampBehavior',
				'createAttribute'=>'createdAt',
				'updateAttribute'=>'updatedAt',
				'setUpdateOnCreate'=>true,
				'timestampExpression'=>"date('Y-m-d H:i:s')",
			)
		);
		return $behaviors;
	}

	public function __get($name) {
		$set = isset($this->getMetaData()->tableSchema->columns[$name]);
		$unix = false;
		$type = '';

		if (!$set) {
			if (strlen($name) > 4 && substr($name, 0, 4) == 'unix') {
				$unix = true;
				$name = strtolower($name[4]) . substr($name, 5);
			}
			$set = isset($this->getMetaData()->tableSchema->columns[$name]);
		}

		if ($set) {
			$type = $this->getMetaData()->tableSchema->columns[$name]->dbType;
		}

		$return = parent::__get($name);
		if (in_array($type, array('date', 'datetime'))) {
			$haystack = array('0000-00-00', '0000-00-00 00:00:00', '');
			if (in_array($return, $haystack)) {
				return null;
			}
			if ($unix) {
				if ($type == "date") {
					return CDateTimeParser::parse($return, 'yyyy-MM-dd');
				} else if ($type == "datetime") {
					$pattern = 'yyyy-MM-dd hh:mm:ss';
					return CDateTimeParser::parse($return, $pattern);
				}
			}
		}
		
		return $return;
	}

	public

	function getMenu($action, $toolbar = false) {
		$name = __CLASS__;
		$user = Yii::app()->user;
		$tool = Yii::app()->request->baseUrl . '/images/toolbars';
		$menu = array();

		$label = "View $name";
		if ($toolbar) $label = "<img src=\"$tool/magnifier-left.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('view', 'id'=>$this->id),
			'visible'=>$action != 'view' && $user->checkAccess("$name.View"),
			'linkOptions'=>array('title'=>'View'),
		);

		$label = "Update $name";
		if ($toolbar) $label = "<img src=\"$tool/pencil.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('update', 'id'=>$this->id),
			'visible'=>$action != 'update' &&
			$user->checkAccess("$name.Update"),
			'linkOptions'=>array('title'=>'Update'),
		);

		$label = "Delete $name";
		if ($toolbar) $label = "<img src=\"$tool/cross-script.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>'#',
			'visible'=>$user->checkAccess("$name.Delete"),
			'linkOptions'=>array(
				'submit'=>array('delete', 'id'=>$this->id),
				'confirm'=>'Are you sure you want to delete this item?',
				'title'=>'Delete',
			)
		);
		return $menu;
	}

}

